package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.CdtsRechargeUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.CdtsRechargeUploadResponse;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.CdtsReversalUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.cdts.passTransaction.CdtsReversalUploadResponse;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.GUID;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.dao.RechargeUploadDao;
import io.renren.modules.basedata.dao.ReversalUploadDao;
import io.renren.modules.basedata.entity.tbl_Operlog;
import io.renren.modules.basedata.entity.tbl_Recharge;
import io.renren.modules.basedata.entity.tbl_Reversal;
import io.renren.modules.basedata.service.RechargeUploadService;
import io.renren.modules.basedata.service.ReversalUploadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class ReversalUploadServiceImpl implements ReversalUploadService {
    private Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ReversalUploadDao reversalUploadDao;
    @Autowired
    OperlogDao operlogDao;
    @Override
    public String reversalUpload() throws Exception {


        log.info("开始获取充正信息");

        List<tbl_Reversal> list = null;

        tbl_Reversal reversal = null;

        list = getReversalList();//获取充正信息

        tbl_Operlog operlog = new tbl_Operlog();

        int operResult=0;

        String fileName = "";

        if(list!=null&&list.size()>0){

            for(int i=0;i<list.size();i++){
                //
                reversal = list.get(i);
//				ReversalUploadRequest request =new ReversalUploadRequest();
                CdtsReversalUploadRequest request = new CdtsReversalUploadRequest();
                request.setId(reversal.getId());
                request.setCardId(reversal.getCardId());
                request.setEffectiveTime(DateUtil.formatDateTimes(reversal.getEffectiveTime()));

//				fileName = ETCCommHelper.getFileName(request,"65");
                request.setReqSender("650101");
                //生成就json文件
//				CreateFileUtil.createJsonFile(request.toJsonStr(), "",fileName);

                try{
//				ReversalUploadResponse response = ETCCommHelper.sdtsUpload(fileName, request, ReversalUploadResponse.class);
                    CdtsReversalUploadResponse response = LwClientHelper.binPostUrl(request);
                    log.info("充正信息返回结果:"+response.toJson());
                    if(response!=null&&response.getInfo().equals("成功！")){

                        //上传成功,更新充正信息表状态

                        if( reversalUploadDao.updateReversal(reversal.getId())==1){
                            log.info("更新充正数据成功");
                            operResult = 1;
                            operlog = getOperlog(34,1,reversal.getId(),fileName ,operResult, response.getInfo(),"上传成功,更新成功");
                        }else{
                            log.info("更新充正数据失败");
                            operlog = getOperlog(34,1,reversal.getId(),fileName ,operResult, response.getInfo(),"上传成功,更新失败");
                            operlogDao.insertlog(operlog);
                            //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                        }

//					sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);

                    }else{

                        log.info("上传冲正信息失败,失败原因:"+response.getInfo());
                        reversalUploadDao.updateReversalError(reversal.getId());
                       // sqlMapClient.update("reversal_ORACLE.updateReversalError",reversal.getId());

                        //getOperlog（操作类型,传输类型,发送文件名,接收文件名,操作结果,部中心返回结果,说明）
                        operlog = getOperlog(34,1,reversal.getId(),fileName ,0, response.getInfo(),response.toJson());
                        operlogDao.insertlog(operlog);
                        //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
                    }
                }catch(IOException e){

                    log.error("上传冲正信息失败,失败原因:"+ e.getMessage());

//				sqlMapClient.update("reversal_ORACLE.updateReversalError",reversal.getId());

                    operlog = getOperlog(34,1,reversal.getId(),fileName ,0, "IO异常","上传冲正信息失败,系统IO异常:"+e.getMessage());
                    operlogDao.insertlog(operlog);
                   // sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);

                    e.printStackTrace();

                    continue;

                }catch (ApiRequestException apie) {

                    log.error("上传冲正信息失败,失败原因:"+ apie.getMessage());

                    if(apie.getErrCode()>=700&&apie.getErrCode()<=800){
                        if(apie.getErrCode()==707){
                            reversalUploadDao.updateReversal(reversal.getId());
                           // sqlMapClient.update("reversal_ORACLE.updateReversal",reversal.getId());
                        }else{
                            reversalUploadDao.updateReversalError(reversal.getId());
                            //sqlMapClient.update("reversal_ORACLE.updateReversalError",reversal.getId());
                        }
                    }

                    operlog = getOperlog(34,1,reversal.getId(),fileName ,0, String.valueOf(apie.getErrCode()),"上传冲正信息失败,系统Apie异常:"+apie.getMessage());
                    operlogDao.insertlog(operlog);
                    //sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);

                    apie.printStackTrace();

                    continue;
                }
            }
            return "上传充正信息结束！";
        }else{

            return "无充正信息,上传结束...";
        }

    }

    //获取充值信息
    @SuppressWarnings("unchecked")
    public List<tbl_Reversal> getReversalList() throws Exception {
        List<tbl_Reversal> list;
        try {

            list = reversalUploadDao.getRechargeList();
            //list = sqlMapClient.queryForList("recharge_ORACLE.getRechargeList");//
        } catch (Exception e1) {
            e1.printStackTrace();
            log.error("获取充值信息失败!错误信息：", e1);
            throw new Exception("获取充值信息失败："+e1.getMessage());
        }
        return list;
    }

    //获取operlog信息
    public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
        tbl_Operlog operlog = new tbl_Operlog();
        operlog.setWastesn(new GUID().toString());
        operlog.setOperTime(new Date());
        operlog.setOpertype(operType);
        operlog.setSoftType(softType);
        operlog.setSendFileName(sendFileName);
        operlog.setReFileName(reFileName);
        operlog.setOperResult(operResult);
        operlog.setReResult(reResult);
        operlog.setContent(content);
        return operlog;
    }
}
